package main

import (
	"fmt"
	"github.com/xuri/excelize/v2"
	"log"
	"os"
	"path/filepath"
	"strconv"
	"strings"
)

func main() {
	if len(os.Args) < 2 {
		fmt.Println("Usage: go run main.go <excelFilePath>")
		return
	}
	excelFilePath := os.Args[1]

	processExcelFile(excelFilePath)
}

func processExcelFile(filePath string) {
	f, err := excelize.OpenFile(filePath)
	if err != nil {
		log.Fatal(err)
	}

	sheetNames := f.GetSheetMap()

	for _, sheetName := range sheetNames {
		rows, err := f.GetRows(sheetName)
		if err != nil {
			log.Println(err)
			continue
		}

		if len(rows) == 0 {
			continue
		}

		var majorIndex int
		for idx, cellValue := range rows[0] {
			if cellValue == "本科专业" {
				majorIndex = idx
				break
			}
		}

		for _, row := range rows[1:] {
			majorStr := row[majorIndex]
			college := row[1]
			saveExcel(college, majorStr)
		}
	}
}

func saveExcel(college string, mList string) {
	majorList := findMajors(mList)
	newFile := excelize.NewFile()

	newFile.SetCellValue("Sheet1", "A1", "code")
	newFile.SetCellValue("Sheet1", "B1", "name")

	currentRow := 2
	idx := 1
	for _, row := range majorList {
		if row == "" {
			continue
		}
		collegeCode := generateCode(idx)
		idx++

		newFile.SetCellValue("Sheet1", "A"+strconv.Itoa(currentRow), collegeCode)
		newFile.SetCellValue("Sheet1", "B"+strconv.Itoa(currentRow), row)
		currentRow++
	}

	// Create the "out" directory if it doesn't exist
	err := os.MkdirAll("out", os.ModePerm)
	if err != nil {
		log.Println(err)
		return
	}

	outPath := filepath.Join("out", college+".xlsx")
	err = newFile.SaveAs(outPath)
	if err != nil {
		log.Println(err)
	}
	fmt.Printf("Saved file: %s\n", outPath)
}

func generateCode(index int) string {
	indexStr := fmt.Sprintf("%02d", index)
	return indexStr
}

func findMajors(input string) []string {
	if strings.Contains(input, "、") {
		return strings.Split(input, "、")
	}
	return []string{input}
}
